package com.grad.webstudy.service.impl;

import com.grad.webstudy.constants.RedisConstants;
import com.grad.webstudy.constants.TokenConstants;
import com.grad.webstudy.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: zjf
 * @Date: 2020/4/2 11:32.
 */
@Service
@EnableScheduling
public class RedisServiceImpl implements RedisService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public void addHotWord(String keyword) {

        if (StringUtils.isEmpty(keyword)) {
            return;
        }
        redisTemplate.opsForZSet().incrementScore(RedisConstants.REDIS_HOT_WORD, keyword, 2000);//添加热词进入redis,2000 增加的数量
        redisTemplate.opsForValue().set(keyword, System.currentTimeMillis());//记录时间
    }

    @Override
    public Map<String, Object> getHotWord(int topN) {

        Set<Object> sets = redisTemplate.opsForZSet()
                .reverseRangeByScore(RedisConstants.REDIS_HOT_WORD, 0, Integer.MAX_VALUE, 0, topN);


        Map<String, Object> result = new HashMap<>();

        result.put("keys", sets);
        List<Integer> score = new ArrayList<>();

        for (Object set : sets) {
            score.add(redisTemplate.opsForZSet().score(RedisConstants.REDIS_HOT_WORD, set).intValue());
        }
        result.put("score", score);
        return result;
    }

    @Override
    public void addCode(String phone, String code) {
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
    }
}
